package com.mm.mindmap.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mm.api.client.UserClient;
import com.mm.common.config.RedisProperties;
import com.mm.common.domain.dto.MessageDTO;
import com.mm.common.domain.dto.UserDTO;
import com.mm.common.domain.po.Result;
import com.mm.common.enums.ResultCode;
import com.mm.common.utils.cacheUtil.CacheClient;
import com.mm.common.utils.DataUtil;
import com.mm.common.utils.SessionHolder;
import com.mm.mindmap.domain.dto.ReplyDTO;
import com.mm.mindmap.domain.po.Reply;
import com.mm.mindmap.mapper.ReplyMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class ReplyServiceImpl extends ServiceImpl<ReplyMapper, Reply>implements IReplyService {
    private final UserClient userClient;
    private final CacheClient cacheClient;
    private final RedisProperties redisProperties;
    private final RabbitTemplate rabbitTemplate;

    public Result sendReply(Reply reply){
        //检验参数
        if(reply == null
                || StrUtil.isBlank(reply.getContent())
                || DataUtil.isNaturalNumInvalid(reply.getRid())
                || DataUtil.isNaturalNumInvalid(reply.getMid())){
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        //添加发生者id
        reply.setPid(SessionHolder.getUser());
        reply.setCreateTime(new Date());
        //初始化
        initialize(reply);
        //4.添加评价进数据库
        saveOrUpdate(reply);

        //发送消息给作者
        try {
            MessageDTO messageDTO = new MessageDTO();
            messageDTO.setRid(reply.getRid());
            messageDTO.setPid(SessionHolder.getUser());
            messageDTO.setContent(reply.getContent());
            messageDTO.setType((short) 1);
            rabbitTemplate.convertAndSend("knowTree.direct", "message.send",JSONUtil.toJsonStr(messageDTO));
        } catch (Exception e) {
            log.warn("解析mindMap的文本出现异常");
            e.printStackTrace();
        }
        //5.返回结果给前端
        return Result.success();
    }


    /** ---------------------------------------------------------------------------------------------------------------------
     * @Method  : TODO
     * @Describe: TODO
     **/

    public Result getAllReply(Long mid){
        //1.检验参数
        if(DataUtil.isNaturalNumInvalid(mid)){
            return Result.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }

        List<ReplyDTO> replyDTOS = cacheClient.queryListPassThrough(redisProperties.cache_reply_list,mid, ReplyDTO.class
                , redisProperties.cache_reply_time, TimeUnit.MINUTES,this::selectAll);


        return Result.success(replyDTOS);
    }

    /* ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 获取所有评论
     * @Describe: TODO
     **/
     private List<ReplyDTO> selectAll(Long mid){
         List<Reply> replyList = lambdaQuery().eq(Reply::getMid, mid).orderByDesc(Reply::getCreateTime).list();
         if(replyList == null || replyList.isEmpty()){
             return new ArrayList<ReplyDTO>();
         }
         List<ReplyDTO> replyDTOS = BeanUtil.copyToList(replyList, ReplyDTO.class);

         //加载用户信息
         for(ReplyDTO replyDTO : replyDTOS){
             UserDTO userDTO = cacheClient.queryPassThrough(redisProperties.cache_user_pre+replyDTO.getPid(),
                     replyDTO.getPid(),UserDTO.class,redisProperties.session_user_save_time, TimeUnit.MINUTES,this::getUser);
             if(userDTO == null){
                 replyDTO.setName(redisProperties.default_name);
                 replyDTO.setAvatar(redisProperties.default_avatar);
             }else {
                 replyDTO.setName(userDTO.getNickname());
                 replyDTO.setAvatar(userDTO.getAvatarUrl());
             }
         }
         return replyDTOS;
     }

    /* ---------------------------------------------------------------------------------------------------------------------
     * @Method  : 获取用户信息
     * @Describe: TODO
     **/
    private UserDTO getUser(Long uid){
        UserDTO userDTO = null;
        try {
            Result result = userClient.userInfo(uid);
            if(ResultCode.SUCCESS.getCode() != result.getCode()){
                log.warn("获取用户信息失败");
                return null;
            }
            userDTO = (UserDTO) result.getData();
        } catch (Exception e) {
            log.warn("获取用户信息失败");
            return null;
        }
        return userDTO;
    }

    private boolean initialize(Reply reply){
        if(reply == null
                || reply.getPid() == null
                || reply.getRid() == null
                || reply.getMid() == null){
            return false;
        }
        if(reply.getLike() == null){
            reply.setLike(0);
        }
        if(reply.getReply2() == null){
            reply.setReply2("");
        }
        if(reply.getContent() == null){
            reply.setContent("");
        }
        if(reply.getCreateTime() == null){
            reply.setCreateTime(new Date());
        }

        return true;
    }
}
